
/**
 * 参数：[socketOpen|socketClose|socketMessage|socketError] = func，[socket连接成功时触发|连接关闭|发送消息|连接错误] 回调
 * timeout：连接超时时间
 * @type {module.webSocket}
 */
export default class webSocket {

  constructor(param = {}) {
      this.param = param;
      this.reconnectCount = 0;
      this.socket = null;
      this.taskRemindInterval = null;
      this.isSucces=false;
  }

  connection = () => {
      let {socketUrl, timeout = 0} = this.param;
      // 检测当前浏览器是什么浏览器来决定用什么socket
      if ('WebSocket' in window) {
          this.socket = new WebSocket(socketUrl);
      }else {
        alert('当前浏览器不支持websocket')
      }
      this.socket.onopen = this.onopen;
      this.socket.onmessage = this.onmessage;
      this.socket.onclose = this.onclose;
      this.socket.onerror = this.onerror;
      this.socket.sendMessage = this.sendMessage;
      this.socket.closeSocket = this.closeSocket;
  };

  // 连接成功触发
  onopen = () => {
      let {socketOpen} = this.param;
      this.isSucces=true;  //连接成功将标识符改为true
      socketOpen && socketOpen();
  };

  // 后端向前端推得数据
  onmessage = (msg) => {
      let {socketMessage} = this.param;
      socketMessage && socketMessage(msg);
  };

  // 关闭连接触发
  onclose = (e) => {
      this.isSucces = false;   //关闭将标识符改为false
      if (this.socket !== null ){
        this.socket.close();
        let {socketClose} = this.param;
        socketClose && socketClose(e);
      }
  };

  // socket连接报错触发
  onerror = (e) => {
      let {socketError} = this.param;
      this.socket = null;
      socketError && socketError(e);
  };
// 向后端发送数据
  sendMessage = (value) => {
      
      if(this.socket) {
        console.log("发送",value)
          this.socket.send(JSON.stringify(value));
      }
  };

  closeSocket = () => {
      this.socket.close();
  };

  //获得状态
  readyState = () => {
      return this.socket.readyState;
  }
};

